//
//  HXLocaleJobTableViewController.m
//  KD
//
//  Created by ifly on 16/4/18.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXLocaleJobTableViewController.h"
#import "HXLocaleJobModel.h"
#import "HXSiteSelectViewController.h"
#import "HXLocaleJobTableViewCell.h"
#import "HXSitePictureViewController.h"
//#import "HXPictureGatherViewController.h"
@interface HXLocaleJobTableViewController ()
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,copy)NSString * nowNetTime;
@property(nonatomic,assign)BOOL isDelete;
@property (nonatomic,copy) NSString * returnTaskId;

//@property (nonatomic,assign) BOOL isFirstLoad;//第一次进入

@end

@implementation HXLocaleJobTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

//    self.isFirstLoad = YES;
//    if (self.isFirstLoad) {
//        
        //进行上传数据
        [self loadCreatePostLocalData];
//        self.isFirstLoad = NO;
    
    
    
    [self.tableView.mj_header beginRefreshing];
    
        NSLog(@"\n------------################--------\n");
        
        self.page = 0;
        self.tableView.tableFooterView = [[UIView alloc]init];
        self.tableView.rowHeight = 78;
        [self.tableView registerNib:[UINib nibWithNibName:@"HXLocaleJobTableViewCell" bundle:nil] forCellReuseIdentifier:@"HXLocaleJobTableViewCell"];
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"map_icon_zoom_in" highImage:@"map_icon_zoom_in_high" target:self action:@selector(rightBtnAction)];
//    }
}

//-------------- 加载数据
-(void)loadCreatePostLocalData{
    
    NSArray * taskIdArr = [HXSendPicModel MR_findAll];
    
    dispatch_queue_t postLocalData = dispatch_queue_create("postLocalData", NULL);
    
    for (HXSendPicModel * picModel in taskIdArr) {
        
        
        dispatch_sync(postLocalData, ^{
            
            NSData * picData = ((HXSendPicContentModel *)picModel.contentModel).contentData;
            NSDictionary * picDic = [NSJSONSerialization JSONObjectWithData:picData options:NSJSONReadingAllowFragments error:nil];
            NSDictionary * dictDic = [picDic objectForKey:@"dict"];
            NSDictionary * modelDic = [picDic objectForKey:@"model"];
            NSString * nowNetworkTime = [modelDic objectForKey:@"SubmitDate"];
            
            if (nowNetworkTime.length <= 0 || nowNetworkTime == nil) {
                
                nowNetworkTime = [GlobalUtil nowTimeDateFormatterWithNowTime:[GlobalUtil getNowPhoneTime]];
            }
            //1.修改小组人员、任务内容（一个工作日内）
            [NetworkAPI changePresonTaskContentWithTaskID:picModel.taskId
                                                 SiteName:[modelDic objectForKey:@"Task_SiteWorkContent"]
                                                GroupName:[modelDic objectForKey:@"Task_GroupName"]
                                               SubmitDate:nowNetworkTime
                                                  Success:^(HXBaseModel *result) {
                                                      if ([result.code isEqualToString:@"200"]) {
                                                          //[SVProgressHUD showSuccessWithStatus:@"修改成功"];
                                                      }
                                                  } failure:^(NSError *err) {
                                                      
                                                  }];

            
            
            [NetworkAPI newCreateAddWithDic:dictDic
                                    success:^(HXSendInformationModel *result) {
                                        if ([result.code integerValue] == 200) {
                                            
                                            //删除数据
                                            for (HXSendPicModel * model in taskIdArr) {
                                                BOOL isDelete = [model MR_deleteEntity];
                                                if (isDelete) {
                                                    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
                                                }
                                            }
                                            
                                        }else{
                                        }
                                    }
                                    failure:^(NSError * err) {
                                    }];

            
        });
    }
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:netWorkIsErrorNotificationGD object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        NSDictionary * dic = note.userInfo;
        NSLog(@"---dic---is----%@---",dic);
        self.returnTaskId = [dic objectForKey:@"taskId"];
    }];
    
    self.tableView.mj_header=[AWRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    self.tableView.mj_footer=[AWRefreshFooder footerWithRefreshingTarget:self refreshingAction:@selector(getMoreData)];
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;
    self.tableView.mj_footer.automaticallyHidden = NO;
    
//    if (!self.isFirstLoad) {
    
        [self.tableView.mj_header beginRefreshing];
//    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)rightBtnAction{
    UIStoryboard *Sb = [UIStoryboard storyboardWithName:@"Apply" bundle:nil];
    HXSiteSelectViewController *Vc = [Sb instantiateViewControllerWithIdentifier:@"HXSiteSelectViewController"];
    [self.navigationController pushViewController:Vc animated:YES];
}
- (void)getData {
    self.page = 0;
    [NetworkAPI localeJobWithNum:[NSString stringWithFormat:@"%ld",(long)self.page]
                            success:^(HXLocaleJobModel *result) {
                                
                                self.returnTaskId = @"";

                                if ([result.code isEqualToString:@"200"]) {
                                    
                                    [self.tableView.mj_footer resetNoMoreData];
                                    [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
                                    [self.tableView.mj_header endRefreshing];
                                    self.page++;
                                    [self.dataArray removeAllObjects];
                                    
                                    for (HXLocaleJobListModel * model in result.resultlist) {
                                        
                                        BOOL isGet = [self panduanTaskIdIsCunZai:model];
                                        HXLocaleJobListModel * data = [[HXLocaleJobListModel alloc] initWithID:model.ID withSiteName:model.SiteName withGroupName:model.GroupName withCreateDate:model.CreateDate withIsGet:isGet];
                                        [self.dataArray addObject:data];
                                    }
                                    
//                                    [self.dataArray addObjectsFromArray:result.resultlist];
                                    [self.tableView reloadData];
                                    if ([result.resultlist count] < 10) {
                                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                        self.tableView.mj_footer.alpha = 1.0f;
                                        return;
                                    }
                                }else if([result.code isEqualToString:@"400"]){
                                    [self.tableView.mj_header endRefreshing];
                                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                    self.tableView.mj_footer.alpha = 1.0f;
                                }else{
                                    [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                    [self loadCreateLocalData];
                                    [self.tableView.mj_header endRefreshing];
                                }

                           } failure:^(NSError *err) {
                               
                               [self loadCreateLocalData];
                               //   [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
                               [self.tableView.mj_header endRefreshing];
                        }];
}

/**在家本地数据*/
-(void)loadCreateLocalData{
    
    if (self.returnTaskId.length > 0) {
        
        NSArray * taskIdArr = [HXSendPicModel MR_findByAttribute:@"taskId" withValue:self.returnTaskId];
        HXSendPicModel * picModel = taskIdArr[0];
        NSData * picData = ((HXSendPicContentModel *)picModel.contentModel).contentData;
        NSDictionary * picDic = [NSJSONSerialization JSONObjectWithData:picData options:NSJSONReadingAllowFragments error:nil];
        NSDictionary * modelDic = [picDic objectForKey:@"model"];
        HXTaskDescribeListModel * model = [[HXTaskDescribeListModel alloc] initWithDictionary:modelDic error:nil];
        HXLocaleJobListModel * localeListModel = [[HXLocaleJobListModel alloc] initWithID:model.ID withSiteName:model.Task_SiteName withGroupName:model.Task_GroupName withCreateDate:model.Task_DateTime withIsGet:YES];
        [self.dataArray insertObject:localeListModel atIndex:0];
        [self.tableView reloadData];
        
        self.returnTaskId = @"";
    }
}

-(void)getMoreData{
    [NetworkAPI localeJobWithNum:[NSString stringWithFormat:@"%ld",(long)self.page]
                         success:^(HXLocaleJobModel *result) {
                             if ([result.code isEqualToString:@"200"]) {
                                 if ([result.resultlist count] == 0) {
                                     [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                     self.tableView.mj_footer.alpha = 1.0f;
                                     return;
                                 }else if ([result.resultlist count] < 10) {
                                     
                                     for (HXLocaleJobListModel * model in result.resultlist) {
                                         
                                         BOOL isGet = [self panduanTaskIdIsCunZai:model];
                                         HXLocaleJobListModel * data = [[HXLocaleJobListModel alloc] initWithID:model.ID withSiteName:model.SiteName withGroupName:model.GroupName withCreateDate:model.CreateDate withIsGet:isGet];
                                         [self.dataArray addObject:data];
                                     }
//                                     [self.dataArray addObjectsFromArray:result.resultlist];
                                     [self.tableView reloadData];
                                     [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                     self.tableView.mj_footer.alpha = 1.0f;
                                 }else {
                                     self.page++;
                                     [self.dataArray addObjectsFromArray:result.resultlist];
                                     [self.tableView reloadData];
                                     [self.tableView.mj_footer endRefreshing];
                                     self.tableView.mj_footer.alpha = 0;
                                 }
                             }else if ([result.code isEqualToString:@"400"]) {
//                                 [self.tableView.mj_header endRefreshing];
                                 [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                 self.tableView.mj_footer.alpha = 1.0f;

                             }else {
                                 [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                 [self.tableView.mj_footer endRefreshing];
                             }
                         } failure:^(NSError *err) {
                             [self.tableView.mj_footer endRefreshing];
                             self.tableView.mj_footer.alpha = 0;
                         }];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HXLocaleJobTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HXLocaleJobTableViewCell" forIndexPath:indexPath];
    HXLocaleJobListModel *data = self.dataArray[indexPath.row];
    cell.data = data;
    
    cell.returnLocaleJobListModel = ^(HXLocaleJobListModel * listModel){
        
        [self.dataArray replaceObjectAtIndex:indexPath.row withObject:listModel];
        [self.tableView reloadData];
    };
    
    return cell;
}

-(BOOL)panduanTaskIdIsCunZai:(HXLocaleJobListModel *)model{

    
    NSArray * taskIdArr = [HXSendPicModel MR_findByAttribute:@"taskId" withValue:model.ID];
    
    if (taskIdArr.count > 0) {
        
        return YES;
    }else{
        
        return NO;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HXLocaleJobListModel *data = self.dataArray[indexPath.row];
    HXSitePictureViewController * hxSitePictVC;
    if (!data.isGet) {
        
        hxSitePictVC = [HXSitePictureViewController CreateSitePictureVCWithTaskID:data.ID withIsAdd:NO withIsListOrRiZhiPush:NO withIsExistTaskId:data.isGet withLocalDataDic:@{}];
        [self.navigationController pushViewController:hxSitePictVC animated:YES];
    }else{
        
        NSArray * taskIdArr = [HXSendPicModel MR_findByAttribute:@"taskId" withValue:data.ID];
        HXSendPicModel * picModel = taskIdArr[0];
        NSData * picData = ((HXSendPicContentModel *)picModel.contentModel).contentData;
        NSDictionary * picDic = [NSJSONSerialization JSONObjectWithData:picData options:NSJSONReadingAllowFragments error:nil];
        
        if (picDic.count > 0) {
            
            hxSitePictVC = [HXSitePictureViewController CreateSitePictureVCWithTaskID:data.ID withIsAdd:NO withIsListOrRiZhiPush:NO withIsExistTaskId:data.isGet withLocalDataDic:picDic];
            [self.navigationController pushViewController:hxSitePictVC animated:YES];
            
        }
    }
}

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    HXLocaleJobListModel *data = self.dataArray[indexPath.row];
    UITableViewRowAction * deleteAtion = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self isDeleteTaskTime:data];
        if (_isDelete == YES) {
            [self.dataArray removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
            [NetworkAPI deleteConstructionSiteTaskWithTaskID:data.ID
                                                     Success:^(HXBaseModel *result) {
                                                         if ([result.code isEqualToString:@"200"]) {
                                                             
                                                             //删除数据
                                                             NSArray * taskIdArr = [HXSendPicModel MR_findByAttribute:@"taskId" withValue:data.ID];
                                                             for (HXSendPicModel * model in taskIdArr) {
                                                                 BOOL isDelete = [model MR_deleteEntity];
                                                                 if (isDelete) {
                                                                     [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
                                                                 }
                                                             }
                                                             
                                                             [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                                                         }
                                                     }
                                                     failure:^(NSError *err) {
                                                         [SVProgressHUD showErrorWithStatus:@"删除失败"];
                                                     }];
        }
        if (_isDelete == NO) {
            UIAlertController * deleteAlertCon = [UIAlertController alertControllerWithTitle:@"提示" message:@"超出可修改时间,无法修改" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * certainBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [tableView reloadData];
            }];
            [deleteAlertCon addAction:certainBtn];
            [self presentViewController:deleteAlertCon animated:YES completion:^{
                
            }];
        }
    }];
    return @[deleteAtion];
}

-(void)isDeleteTaskTime:(HXLocaleJobListModel *)model{
    
    //获取网络时间
    [NetworkAPI getServerDateSuccess:^(HXServerDateModel *result) {
        if ([result.code isEqualToString:@"200"]) {
            _nowNetTime = [NSString stringWithFormat:@"%@",result.ServerDate];
            NSLog(@"网络时间数据==================%@",result.ServerDate);
        }
    } failure:^(NSError *err) {
        [SVProgressHUD showErrorWithStatus:@"获取网络时间失败,请检查网络"];
    }];
    //当前时间秒数
    NSDate* nowDate = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval nowTimeSecond=[nowDate timeIntervalSince1970] * 1000;
    NSString * nowTimeString = [NSString stringWithFormat:@"%.0f",nowTimeSecond];
    //将列表时间转化为Date数据
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *cellTimeDate = [dateformatter dateFromString:model.CreateDate];
    //将Date数据转化为星期几
    //将列表时间转化为秒数 将秒转化为毫秒 *1000
    NSTimeInterval oneDay = 24*60*60*1; //1天的长度
    NSTimeInterval NowSecond=[cellTimeDate timeIntervalSince1970] * 1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", NowSecond];
    
    NSInteger dis = 1; //前后的天数
    if (([timeString integerValue] + (dis * oneDay * 1000)) >= [nowTimeString integerValue]) {
            self.isDelete = YES;
    }
    else {
        self.isDelete = NO;
    }
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}

#pragma mark - 懒加载
- (NSMutableArray<HXLocaleJobListModel *> *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

-(NSMutableArray<HXGetAreaCodeTestModelList *>*)testDataArray {
    if (_testDataArray == nil) {
        _testDataArray = [[NSMutableArray alloc] init];
    }
    return _testDataArray;
}





@end
